//
//  BannerView.m
//  DetailNSNULL
//
//  Created by 蓓蕾 on 2021/7/27.
//  Copyright © 2021 YangYang. All rights reserved.
//

#import "BannerView.h"
//#import "BannerControlView.h"

@interface BannerView ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *mainScrollView;

@property (nonatomic, strong) BannerControlView *controlView;

@property (nonatomic, strong) NSArray *originalImageNameArr;

@property (nonatomic, strong) NSMutableArray *imageViewArr;
@property (nonatomic, strong) NSMutableArray *imageNameArr;

@property (nonatomic, strong) NSString *currentImageName;

@property (nonatomic, assign) BOOL fromZuoDaoYOu;
@property (nonatomic,assign) dispatch_source_t timer;
@property (nonatomic,assign) BOOL isHangUp;//计时器是否挂起

@end

@implementation BannerView

-(id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _autoScrollTime = 3.0;
    }
    return self;
}

-(void)setLocalImageArr:(NSArray *)localImageArr
{
    _localImageArr = localImageArr;
    _originalImageNameArr = localImageArr;
    _imageViewArr = [NSMutableArray new];
    _imageNameArr = [NSMutableArray arrayWithArray:_originalImageNameArr];
    NSString *lastName = [_imageNameArr lastObject];
    [_imageNameArr removeObject:lastName];
    [_imageNameArr insertObject:lastName atIndex:0];
    
    [self initBannerView:localImageArr.count];
    [self setupTimer];
}
-(void)initBannerView:(NSInteger)imageCount{
    
    NSInteger count = imageCount > 3 ? 3 : imageCount;
    _mainScrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
    if (_directionType == HorizontalDirectionType) {
        _mainScrollView.contentSize=CGSizeMake(count * CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
    }
    else
    {
        _mainScrollView.contentSize=CGSizeMake(CGRectGetWidth(self.bounds), count * CGRectGetHeight(self.bounds));
    }
    
    _mainScrollView.scrollEnabled = YES;
    _mainScrollView.bounces = NO;
    _mainScrollView.delegate = self;
    _mainScrollView.pagingEnabled = YES;
    _mainScrollView.showsHorizontalScrollIndicator = NO;
    _mainScrollView.showsVerticalScrollIndicator = NO;
    if (@available(iOS 11.0, *)){
        [_mainScrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
        
    }
    [self addSubview:_mainScrollView];
    
    for(int i=0;i<count;i++){
        UIImageView * imageView=[[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.bounds)*i, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
        if (_directionType == HorizontalDirectionType) {
            imageView.frame = CGRectMake(CGRectGetWidth(self.bounds)*i, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
        }
        else
        {
            imageView.frame = CGRectMake(0, CGRectGetHeight(self.bounds) * i, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
        }
        NSString * imageName;
        imageName= _imageNameArr[i];
        UIImage * image=[UIImage imageNamed:imageName];
        [imageView setImage:image];
        [_mainScrollView addSubview:imageView];
        [_imageViewArr addObject:imageView];
    }
    if (_directionType == HorizontalDirectionType) {
        [_mainScrollView setContentOffset:CGPointMake(CGRectGetWidth(self.bounds), 0) animated:NO];
    }
    else
    {
        [_mainScrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.bounds)) animated:NO];
    }
    NSLog(@"_imageNameArr = %@",_imageNameArr);
    
    
    _controlView = [[BannerControlView alloc] init];
    [self addSubview:_controlView];
    _controlView.locationType = _locationType;
    _controlView.shapeType = _shapeType;
    _controlView.currentDotColor = [UIColor purpleColor];
    _controlView.dotCount = _originalImageNameArr.count;
    if (_locationType == RightCenterType) {
        [_controlView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_top).mas_offset(0);
            make.right.mas_equalTo(self.mas_right).mas_offset(0);
            make.bottom.mas_equalTo(self.mas_bottom).mas_offset(-10);
        }];
    }
    else
    {
        [_controlView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).mas_offset(0);
            make.right.mas_equalTo(self.mas_right).mas_offset(0);
            make.bottom.mas_equalTo(self.mas_bottom).mas_offset(-10);
        }];
    }
    __weak typeof(self) weakSelf = self;
    _controlView.CurrentDotIndexChangedBlock = ^(NSInteger index) {
        NSLog(@"index = %ld",index);
        [weakSelf autoScroll:index];
        
    };
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!_isHangUp) {
        NSLog(@"暂停计时器");
        [self invalidateTimer];
        _isHangUp = YES;
    }
    
    
    CGPoint translatedPoint = [scrollView.panGestureRecognizer translationInView:scrollView];
    if (_directionType == HorizontalDirectionType) {
        if(translatedPoint.x < 0)
        {
            _fromZuoDaoYOu = NO;
//            NSLog(@"由右向左滑动");
        }
        if(translatedPoint.x > 0)
        {
            _fromZuoDaoYOu = YES;
//            NSLog(@"由左向右滑动");
        }
    }
    else
    {
        if (translatedPoint.y > 0) {
            _fromZuoDaoYOu = YES;
//            NSLog(@"由上向下滑");
            
        }
        if (translatedPoint.y< 0) {
            _fromZuoDaoYOu = NO;
//            NSLog(@"由下向上滑");
        }
    }
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    CGFloat width = scrollView.frame.size.width;
    CGFloat offsetX = scrollView.contentOffset.x;
    // 当前位置需要显示的控制器的索引
    NSInteger index = offsetX / width;
    if (_directionType == HorizontalDirectionType) {
        
    }
    else
    {
        width = scrollView.frame.size.height;
        offsetX = scrollView.contentOffset.y;
        // 当前位置需要显示的控制器的索引
        index = offsetX / width;
    }
//    NSLog(@"index = %ld",index);
//    NSLog(@"offsetX = %lf",offsetX);
    
    
    
    if (_fromZuoDaoYOu) {
        NSString *lastImageName = [_imageNameArr lastObject];
        [_imageNameArr removeObject:lastImageName];
        [_imageNameArr insertObject:lastImageName atIndex:0];
    }
    else
    {
        NSString *firstImageName = [_imageNameArr firstObject];
        [_imageNameArr removeObject:firstImageName];
        [_imageNameArr insertObject:firstImageName atIndex:(_originalImageNameArr.count - 1)];
    }
    
    for (NSInteger i = 0; i < _imageViewArr.count; ++i) {
        NSString *imageName = _imageNameArr[i];
        UIImageView *imageView = _imageViewArr[i];
        imageView.image = [UIImage imageNamed:imageName];
    }
    NSString *currentImageName = [_imageNameArr objectAtIndex:1];
    _currentImageName = currentImageName;
    NSInteger currentIndex = [_originalImageNameArr indexOfObject:currentImageName];
//    NSLog(@"_imageNameArr = %@",_imageNameArr);
    NSLog(@"currentIndex = %ld",currentIndex);
    _controlView.currentDotIndex = currentIndex;
    if (_directionType == HorizontalDirectionType) {
        [scrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.bounds)) animated:NO];
    }
    else
    {
        [scrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.bounds)) animated:NO];
    }
    
    if (_isHangUp) {
        NSLog(@"继续计时器");
        [self setupTimer];
        _isHangUp = NO;
    }
    
    
}

-(void)autoScroll:(NSInteger)index
{
    if (index < 1) {
        [self.imageNameArr removeAllObjects];
        [self.imageNameArr addObjectsFromArray:self.originalImageNameArr];
        NSString *lastName = [self.imageNameArr lastObject];
        [self.imageNameArr removeObject:lastName];
        [self.imageNameArr insertObject:lastName atIndex:0];
    }
    else if (index > 1)
    {
        [self.imageNameArr removeAllObjects];
        [self.imageNameArr addObjectsFromArray:self.originalImageNameArr];
        NSArray *subArr1 = [self.imageNameArr subarrayWithRange:NSMakeRange(0, index - 1)];
        NSArray *subArr2 = [self.imageNameArr subarrayWithRange:NSMakeRange(index - 1, self.originalImageNameArr.count - index + 1)];
//        NSLog(@"subArr1 = %@",subArr1);
//        NSLog(@"subArr2 = %@",subArr2);
        [self.imageNameArr removeAllObjects];
        [self.imageNameArr addObjectsFromArray:subArr2];
        [self.imageNameArr addObjectsFromArray:subArr1];
    }
    else
    {
        [self.imageNameArr removeAllObjects];
        [self.imageNameArr addObjectsFromArray:self.originalImageNameArr];
    }
    
    if (self.directionType == HorizontalDirectionType) {
        [self.mainScrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.bounds)) animated:NO];
    }
    else
    {
        [self.mainScrollView setContentOffset:CGPointMake(0,(index + 1) * CGRectGetHeight(self.bounds)) animated:YES];
        [UIView animateWithDuration:0.2 animations:^{
            
        } completion:^(BOOL finished) {
            for (NSInteger i = 0; i < self.imageViewArr.count; ++i) {
                NSString *imageName = self.imageNameArr[i];
                UIImageView *imageView = self.imageViewArr[i];
                imageView.image = IMAGE(imageName);
                
            }
            NSString *currentImageName = [self.imageNameArr objectAtIndex:1];
            _currentImageName = currentImageName;
            NSInteger currentIndex = [self.originalImageNameArr indexOfObject:currentImageName];
        //    NSLog(@"_imageNameArr = %@",self.imageNameArr);
        //    NSLog(@"currentIndex = %ld",currentIndex);
            self.controlView.currentDotIndex = currentIndex;
            if (self.directionType == HorizontalDirectionType) {
                [self.mainScrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.bounds)) animated:NO];
            }
            else
            {
                [self.mainScrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.bounds)) animated:NO];
            }
        }];
        
    }
    
    
}

#pragma mark - GCD定时器
/// 开启计时器
- (void)setupTimer{
    if (self.timer) {
        NSLog(@"继续计时器");
        [self kj_bannerResumeTimer:self.timer];
    }else{
        NSLog(@"重新创建计时器");
        __weak __typeof(self) weakself = self;
        self.timer = [self kj_bannerCreateAsyncTimer:YES Task:^{
            __strong __typeof(self) strongself = weakself;
            NSLog(@"走这里了");
            dispatch_async(dispatch_get_main_queue(), ^{
                NSInteger currentIndex = [strongself.originalImageNameArr indexOfObject:strongself.currentImageName];
                currentIndex++;
                [strongself autoScroll:currentIndex];
            });
            
            
        } start:self.autoScrollTime/2. interval:self.autoScrollTime repeats:YES];
    }
}
/// 释放计时器
- (void)invalidateTimer{
    if (self.timer) {
        [self kj_bannerStopTimer:self.timer];
        _timer = nil;
    }
}
/// 暂停计时器滚动处理
- (void)kj_pauseTimer{
    if (self.timer) {
        [self kj_bannerPauseTimer:self.timer];
    }
}
/// 继续计时器滚动
- (void)kj_repauseTimer{
    if (self.timer) {
        [self kj_bannerResumeTimer:self.timer];
    }
}

/* 创建异步定时器 */
- (dispatch_source_t)kj_bannerCreateAsyncTimer:(BOOL)async
                                          Task:(void(^)(void))task
                                         start:(NSTimeInterval)start
                                      interval:(NSTimeInterval)interval
                                       repeats:(BOOL)repeats{
    if (!task || start < 0 || (interval <= 0 && repeats)) return nil;
    self.isHangUp = NO;
    dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
    __block dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
    __weak __typeof(self) weaktarget = self;
    dispatch_source_set_event_handler(timer, ^{
        if (weaktarget == nil) {
            dispatch_source_cancel(timer);
            timer = nil;
        }else{
            if (repeats) {
                task();
            }else{
                task();
                [weaktarget kj_bannerStopTimer:timer];
            }
        }
    });
    dispatch_resume(timer);
    return timer;
}
/* 取消计时器 */
- (void)kj_bannerStopTimer:(dispatch_source_t)timer{
    self.isHangUp = NO;
    if (timer) {
        dispatch_source_cancel(timer);
        timer = nil;
    }
}
/* 暂停计时器 */
- (void)kj_bannerPauseTimer:(dispatch_source_t)timer{
    if (timer) {
        self.isHangUp = YES;
        dispatch_suspend(timer);
    }
}
/* 继续计时器 */
- (void)kj_bannerResumeTimer:(dispatch_source_t)timer{
    if (timer && self.isHangUp) {
        self.isHangUp = NO;
        //挂起的时候注意，多次暂停的操作会导致线程锁的现象
        //dispatch_suspend和dispatch_resume是一对
        dispatch_resume(timer);
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
